<template>
  <div class="system-token-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-token-search mb15">
        <el-input size="default" placeholder="请输入客户端ID" style="max-width: 180px" v-model="state.tableData.param.clientId" clearable>
        </el-input>
        <el-input size="default" placeholder="请输入用户ID" style="max-width: 180px" v-model="state.tableData.param.userId" clearable>
        </el-input>
        <el-select v-model="state.tableData.param.tokenType" placeholder="请选择令牌类型" clearable style="max-width: 180px">
          <el-option label="访问令牌" value="access"></el-option>
          <el-option label="刷新令牌" value="refresh"></el-option>
        </el-select>
        <el-select v-model="state.tableData.param.status" placeholder="请选择状态" clearable style="max-width: 180px">
          <el-option label="活跃" value="active"></el-option>
          <el-option label="已过期" value="expired"></el-option>
          <el-option label="已撤销" value="revoked"></el-option>
        </el-select>
        <el-button size="default" type="primary" class="ml10" @click="getTableData">
          <el-icon>
            <ele-Search />
          </el-icon>
          查询
        </el-button>
        <el-button size="default" type="danger" class="ml10" @click="onBatchRevoke" :disabled="state.multipleSelection.length === 0">
          <el-icon>
            <ele-Delete />
          </el-icon>
          批量撤销
        </el-button>
      </div>
      <el-table 
        :data="state.tableData.data" 
        v-loading="state.tableData.loading" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="tokenId" label="令牌ID" show-overflow-tooltip width="200">
          <template #default="scope">
            <el-tooltip :content="scope.row.tokenId" placement="top">
              <span>{{ scope.row.tokenId.substring(0, 20) }}...</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="clientId" label="客户端ID" show-overflow-tooltip></el-table-column>
        <el-table-column prop="username" label="用户名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="tokenType" label="令牌类型" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.tokenType === 'access' ? 'primary' : 'success'" size="small">
              {{ scope.row.tokenType === 'access' ? '访问令牌' : '刷新令牌' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scopes" label="作用域" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-for="scopeItem in scope.row.scopes" :key="scopeItem" size="small" class="mr5 mb5">
              {{ scopeItem }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" show-overflow-tooltip>
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 'active' ? 'success' : scope.row.status === 'expired' ? 'warning' : 'danger'" 
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expiresAt" label="过期时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button 
              size="small" 
              text 
              type="danger" 
              @click="onRevokeToken(scope.row)"
              :disabled="scope.row.status === 'revoked'"
            >
              <el-icon>
                <ele-Delete />
              </el-icon>
              撤销
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="onHandleSizeChange"
        @current-change="onHandleCurrentChange"
        class="mt15"
        :pager-count="5"
        :page-sizes="[5, 20, 30]"
        v-model:current-page="state.tableData.param.page"
        background
        v-model:page-size="state.tableData.param.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>
    
    <!-- 批量撤销对话框 -->
    <el-dialog title="批量撤销令牌" v-model="state.batchRevokeDialog.visible" width="500px">
      <el-form :model="state.batchRevokeDialog.form" label-width="80px">
        <el-form-item label="撤销原因">
          <el-input 
            v-model="state.batchRevokeDialog.form.reason" 
            type="textarea" 
            placeholder="请输入撤销原因"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div class="batch-info">
            <p>将撤销 <strong>{{ state.multipleSelection.length }}</strong> 个令牌</p>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.batchRevokeDialog.visible = false">取 消</el-button>
          <el-button type="danger" @click="confirmBatchRevoke">确认撤销</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="oidcTokens">
import { reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getTokenList, revokeToken, batchRevokeTokens } from '/@/api/oidc/tokens';

// 定义变量内容
const state = reactive({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      page: 1,
      size: 5,
      clientId: '',
    userId: '',
    tokenType: '',
      status: '',
    },
  },
  multipleSelection: [],
  batchRevokeDialog: {
    visible: false,
    form: {
      reason: '',
    },
  },
});

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    active: '活跃',
    expired: '已过期',
    revoked: '已撤销',
  };
  return statusMap[status] || status;
};

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  getTokenList(state.tableData.param)
    .then((res: any) => {
      state.tableData.data = res.data.items;
      state.tableData.total = res.data.total;
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

// 处理多选
const handleSelectionChange = (selection: any[]) => {
  state.multipleSelection = selection;
};

// 撤销单个令牌
const onRevokeToken = (row: any) => {
  ElMessageBox.confirm(`确定要撤销令牌 "${row.tokenId}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      revokeToken(row.id,row.tokenType).then(() => {
        ElMessage.success('撤销成功');
        getTableData();
      });
    })
    .catch(() => {});
};

// 打开批量撤销对话框
const onBatchRevoke = () => {
  if (state.multipleSelection.length === 0) {
    ElMessage.warning('请选择要撤销的令牌');
    return;
  }
  state.batchRevokeDialog.visible = true;
  state.batchRevokeDialog.form.reason = '';
};

// 确认批量撤销
const confirmBatchRevoke = () => {
  const accessTokenIds = state.multipleSelection.filter((item: any) => item.tokenType === 'access').map((item: any) => item.id);
  const refreshTokenIds = state.multipleSelection.filter((item: any) => item.tokenType === 'refresh').map((item: any) => item.id);
  const params = {
    accessTokenIds: accessTokenIds,
    refreshTokenIds: refreshTokenIds,
    reason: state.batchRevokeDialog.form.reason || '管理员批量撤销',
  };
  
  batchRevokeTokens(params)
    .then((res: any) => {
      ElMessage.success(`批量撤销成功，共撤销 ${res.data.revokedCount} 个令牌`);
      state.batchRevokeDialog.visible = false;
      getTableData();
    })
    .catch(() => {
      state.batchRevokeDialog.visible = false;
    });
};

// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.size = val;
  getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.page = val;
  getTableData();
};

// 页面加载时
onMounted(() => {
  getTableData();
});
</script>

<style scoped lang="scss">
.system-token-container {
  .system-token-search {
    display: flex;
    margin-bottom: 10px;
    .el-input,
    .el-select {
      margin-right: 10px;
    }
  }
  
  .batch-info {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    p {
      margin: 0;
      color: #606266;
    }
  }
}
</style>